package vip.xumy.core.pojo.com;

import java.util.Date;

import vip.xumy.core.utils.DateUtil;

/**	All rights reserved
 *	author:mengyxu
 *	date:2019年6月26日
 */

@SuppressWarnings("unchecked")
public class Cache {
	
	private Object value;
	private Long timeout;
	private Long loseTime;
	
	public <T> Cache(T value) {
		this.value = value;
	}
	
	public <T> Cache(T value, long timeout) {
		this.value = value;
		this.timeout = timeout;
		this.loseTime = System.currentTimeMillis() + timeout*1000;
	}
	
	public <T> T getValue() {
		if(loseTime != null && System.currentTimeMillis() > loseTime) {
			return null;
		}
		return (T)value;
	}
	
	public String getLoseTime() {
		if(loseTime == null) {
			return "永不失效";
		}
		return DateUtil.format(new Date(loseTime), DateUtil.FORMAT19_LINE_YYYYMMDDHHMMSS);
	}
	
	public void refresh() {
		if(timeout != null) {
			this.loseTime = System.currentTimeMillis() + timeout*1000;
		}	
	}
	
	public static boolean isEmpty(Cache cache) {
		return cache == null || cache.getValue() == null;
	}
	
	public static void setLoseTime(Cache cache,Long loseTime) {
		cache.loseTime = loseTime;
	}

}
